import { baseUrl, appid } from '@/js/config/index.js'
import AXIOS from '@/utils/request.js'
// 微信小程序方法

/**
 * 检测sessionkey是否过期
 */
const checkSessionKey = () => {
	return new Promise((resolve, reject) => {
		const session_key = uni.getStorageSync('session_key') // 用户缓存信息
		if (session_key) {
			uni.checkSession({
				success() {
					resolve(true) //状态未过期
				},
				fail() {
					resolve(false) //状态已过期
				}
			})
		} else {
			resolve(false) //未存贮
		}
	})
}


/**
 * 登录
 */
export const loginHandle = function(type) {
	let _this = this
	return new Promise(function(resolve, reject) {
		// checkSessionKey().then(isLogin => {
		if (!uni.getStorageSync('openid')) {
			getOpenId().then(res => {
				resolve(res)
			})
		} else {
			let openid = uni.getStorageSync('openid')
			resolve(openid)
		}
		// })
	})
}

const getOpenId = () => {
	return new Promise(function(resolve, reject) {
		wx.login({
			success: res => {
				uni.request({
					url: baseUrl + '/order/order/openid/' + res.code,
					method: 'get',
					success: result => {
						if (result.data.code === 200) {
							uni.setStorageSync('openid', result.data.data)
							resolve(result.data.data)
						} else {
							uni.showToast({
								title: result.data.msg,
								icon: 'none'
							})
							reject()
						}
					},
					fail: error => {
						console.log('错误信息:', error)
					}
				})
			},
			fail: error => {
				console.log(error)
			}
		})
	})
}

/**
 * 微信数据解密
 */
export const WXBizDataCrypt = function(data) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + '/login/login/phone/' + data.code,
			method: 'get',
			success: result => {
				console.info('result', result)
				if (result.data.code === 200) {
					let res = result.data
					resolve(res)
				} else {
					reject(result.data.msg)
					uni.navigateTo({ url: '/pages/login/login' })
				}
			}
		})
	})
}

/**
 * 获取用户信息
 */
export const getUserInfo = function() {
	return new Promise((resolve, reject) => {
		let _this = this
		AXIOS.request(true, 'get', {
				url: '/member/member/info'
			},
			function(res) {
				// if (res.status === 1) {
				resolve(res.data)
				// } else {
				// 	reject()
				// }

			},
			function(error) {
				reject()
			}
		)
	})
}


/**
 * 设置用户头像昵称
 */
export const setUserInfo = function(params) {
	return new Promise((resolve, reject) => {
		AXIOS.request(false, 'post', {
				url: '/Home/Users/setHeadimgNickname',
				data: params
			},
			function(res) {
				if (res.status === 1) {
					resolve(res)
				} else {
					reject(res.msg)
				}
			},
			function(err) {
				reject(err)
			}
		)
	})
}